package cn.kk.pzhu.gpaweb.controller;

import cn.kk.pzhu.gpaweb.dao.GpaMapper;
import cn.kk.pzhu.gpaweb.dao.StudentMapper;
import cn.kk.pzhu.gpaweb.entity.QueryVo;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author KK
 * @CreateTime 2022-09-17
 */
@Controller
public class AdminHandler {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private GpaMapper gpaMapper;

    @RequestMapping("/admin")
    @ResponseBody
    public ModelAndView admin(ModelAndView m) {
        m.addObject("claList", studentMapper.getClaList());
        m.addObject("majorList", studentMapper.getMajorList());
        m.setViewName("adminDownload");
        return m;
    }

    @RequestMapping("/getAll")
    @ResponseBody
    public List<QueryVo> getAll(@RequestParam("cla") String cla, @RequestParam("major") String major, @RequestParam("time") String time, @RequestParam("classes") String classes) {
        return gpaMapper.getAll(cla, major, time, classes);
    }

    @RequestMapping("/getExcel")
    public void download(HttpServletRequest request, HttpServletResponse response, @RequestParam("cla") String cla, @RequestParam("major") String major, @RequestParam("time") String time, @RequestParam("classes") String classes) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(String.format("%s级%s%s班-%s年度绩点汇总",cla,major,classes,time), "UTF-8") + ".xls");
        //编码
        response.setCharacterEncoding("UTF-8");
        List<QueryVo> list = gpaMapper.getAll(cla, major, time, classes);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), QueryVo.class, list);
        workbook.write(response.getOutputStream());
    }
}
